package com.qf.security;

import com.qf.mapper.PermissionMapper;
import com.qf.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/5/8
 * @desc
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 这个方法,登录请求发出时,框架会自动调用,根据用户名查找用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.qf.entity.User user2 = userMapper.getUserByUserName(username);
        if (user2 == null) {
            // 这个异常是SpringSecurity提供的
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        Set<String> set = permissionMapper.selectByUserId(user2.getId());
        Set<GrantedAuthority> auths = new HashSet<>();
        // 遍历权限集合，添加到auths中
        set.forEach(item -> {
            if (StringUtils.hasText(item)) {
                auths.add(new SimpleGrantedAuthority(item));
            }
        });
        // 此处的User是SpringSecurity提供的，User对象包含了用户名、密码、权限等信息
        User user = new User(user2.getUsername(), user2.getPassword(), auths);
        System.out.println("user = " + user);
        return user;
    }
}
